﻿--[[
	This file is part of FlexBar3.

	FlexBar3 is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	FlexBar3 is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with FlexBar3.  If not, see <http://www.gnu.org/licenses/>.
]]
-- Keep a list of registered modules
local ModuleList = {};
FlexBar3.ModuleList = ModuleList;

-- Local upvalues
local tinsert = tinsert;
local FlexBar3 = FlexBar3;
local assert = assert;
local type = type;

-- Table that contains the order in which libs will be loaded (or were loaded)
local LoadOrder = {};
FlexBar3.LoadOrder = LoadOrder;

-- Function to create new modules
function FlexBar3:NewModule(Name, Table)
	local Module = Table or {};
	ModuleList[Name] = Module;
	tinsert(LoadOrder, Name);
	return Module;
end

function FlexBar3:GetModule(Name)
	return ModuleList[Name];
end

function FlexBar3:EnableModules()
	for Key = 1, #LoadOrder do
		self:EnableModule(LoadOrder[Key]);
	end
end

function FlexBar3:DisableModules()
	local Key = #LoadOrder;
	while(Key >= 1) do
		self:DisableModule(LoadOrder[Key]);
		Key = Key - 1;
	end
end


-- Enable a module and enable its depencies if needed
function FlexBar3:EnableModule(ModuleName, Module)
	self:Debug(("Attempting to enable module: %s"):format(ModuleName));
	if(self:IsModuleEnabled(ModuleName)) then return true; end
	local Module = Module or self:GetModule(ModuleName);
	-- Assert check for module existance
	assert(Module, ("Failure to enable [%s]: Module not found"):format(ModuleName), 2);
	if(not FlexBar3.DB.Modules) then
		FlexBar3.DB.Modules = {};
	end
	local ModulesDB = FlexBar3.DB.Modules;
	if(not ModulesDB[ModuleName]) then
		FlexBar3:Debug(("No database found for %s, initializing a new one"):format(ModuleName));
		ModulesDB[ModuleName] = { Enabled = true, DB = {}};
	end
	Module.DB = ModulesDB[ModuleName].DB;
	local Enable = Module.Enable;
	if(type(Enable) == "function") then Module.Enable(Module); end
	Module.Enabled = true;
end

function FlexBar3:DisableModule(ModuleName, Module)
	if(not self:IsModuleEnabled(ModuleName)) then return true; end
	local Module = Module or self:GetModule(ModumeName);
	assert(Module, ("Failure to enable [%s]: Module not found"):format(ModuleName, 2));
	local Disable = Module.Disable;
	if(type(Disable) == "function") then Module.Disable(Module); end
	Module.Enabled = false;
end

function FlexBar3:IsModuleEnabled(Module)
	if(type(Module) == "string") then
		Module = self:GetModule(Module);
	end
	if(type(Module) ~= "table") then
		return nil;
	end
	return Module.Enabled or false;
end
